# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/21'
__author__ = 'Just'
__filename__ = 'banner'
"""
from sqlalchemy import Column, Integer, String, orm, or_, SmallInteger
from app.libs.common import get_current_time
from app.libs.error_code import NotFoundException, ParameterException
from app.model.banner_item import BannerItem
from app.model.base import BaseModel, db


class Banner(BaseModel):
    """轮播位模型"""
    __tablename__ = 'banner'

    id = Column(SmallInteger, primary_key=True, autoincrement=True)
    name = Column(String(50), comment='名称')
    description = Column(String(255), comment='简介')
    update_time = Column(Integer, comment='修改时间')

    # 一对多 带一组轮播item
    items = db.relationship('BannerItem',  backref='banner_item', lazy='dynamic')

    @orm.reconstructor
    def __init__(self):
        # 序列化列表
        self.fields = ['id', 'name',
                       'description', 'update_time',
                       'create_time', 'status'
                       ]

    @staticmethod
    def banners_for_user():
        """普通客户端 获取轮播位列表"""
        banners = Banner.query.filter(Banner.status == 1).all()
        return banners

    @staticmethod
    def banners_for_admin():
        """给后台 获取轮播位列表"""
        banners = Banner.query.all()
        return banners

    @staticmethod
    def add_banner(params):
        """
        管理员添加一条新的轮播位信息
        :param params: 包括 name description update_time
        :return:
        """
        has = Banner.query.filter(Banner.name == params['name']).first()
        if has:
            raise ParameterException(msg='已经存在同名Banner, 添加失败', error_code=2001)
        else:
            with db.auto_commit():
                # 新建
                banner = Banner()
                banner.name = params['name']
                banner.description = '未添加描述信息' if params['description'] is None else params['description']
                banner.update_time = get_current_time()
                db.session.add(banner)

    @staticmethod
    def update_banner(bid, params):
        """
        更新
        :param bid: 更新的id条目
        :param params: 包括 name description update_time
        :return:
        """
        banner = Banner.query.get_or_404(bid, msg='此id号 banner栏不存在', error_code=2000)
        with db.auto_commit():
            if params['name'] != banner.name:
                banner.name = params['name']
            banner.description = '未添加描述信息' if params['description'] is None else params['description']
            banner.update_time = get_current_time()
